package com.hjt.gulimall.ware.listener;

import com.hjt.common.to.mq.OrderTo;
import com.hjt.common.to.mq.StockLockedTo;
import com.hjt.gulimall.ware.constant.RabbitMqConstant;
import com.hjt.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author:97007
 * @date:2021/10/14 16:12
 */
@RabbitListener(queues = {RabbitMqConstant.STOCK_RELEASE_QUEUE_NAME})
@Service
@Slf4j
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 监听库存释放的消息
     * 1.库存自动解锁
     *  库存解锁
     * 1）下单成功，没有支付自动取消或者用户手动取消，都要解锁
     * 2）库存锁定成功，但是下单中后续步骤失败，订单回滚，也要解锁库存。
     * @param message
     * @param channel
     * @param lockedTo
     */
    @RabbitHandler
    public void handleStockRelease(Message message, Channel channel, StockLockedTo lockedTo) throws IOException {
        log.info("收到库存释放消息"+lockedTo);
        try {
            wareSkuService.unlock(lockedTo);
            // 解锁成功，
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("库存解锁成功");
        } catch (Exception e) {
            e.printStackTrace();
            // 出现异常，拒绝消息
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    /**
     * 监听订单关闭的消息，订单关闭，库存要解锁
     * @param message
     * @param channel
     * @param orderTo
     * @throws IOException
     */
    @RabbitHandler
    public void handleOrderRelease(Message message, Channel channel, OrderTo orderTo) throws IOException {
        log.info("收到订单释放消息"+orderTo);
        try {
            wareSkuService.unlock(orderTo);
            // 解锁成功，
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("库存解锁成功");
        } catch (Exception e) {
            e.printStackTrace();
            // 出现异常，拒绝消息
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
